package com.cckj.projectapi.module.open.service;

import com.cckj.projectapi.module.open.vo.PhoneLoginVo;
import com.cckj.common.base.LoginUserEntity;
import com.cckj.common.customAssert.AssertCustom;
import com.cckj.common.response.ResultData;
import com.cckj.common.sms.SmsConfig;
import com.cckj.common.service.JwtTokenService;
import com.cckj.common.utils.EasyBootUtil;
import com.cckj.common.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * xxx
 *
 * @author chengni
 * @date 2021/8/20 上午9:46
 */
@Slf4j
@Service
public class CommonService {

    @Resource
    SmsConfig smsConfig;

    @Resource
    RedisUtils redisUtils;

    @Resource
    JwtTokenService jwtTokenService;

    public ResultData getSmsCode(String phone) {
        AssertCustom.notNull(phone, "手机号不能为空");
        AssertCustom.isTrue(EasyBootUtil.validPhone(phone), "手机号格式不正确");

        String randomCode = EasyBootUtil.randomCode();

        // 短信配置类 发送短信；

        // 缓存到redis
        redisUtils.set(smsRedisKey(phone), randomCode, smsConfig.getExpirationMinutes(), smsConfig.getExpirationTimeUnit());

        return ResultData.ok(randomCode);
    }

    private String smsRedisKey(String phone) {
        return smsConfig.getRedisKsy() + ":" + phone;
    }


    public ResultData phoneLogin(PhoneLoginVo vo) {
        Object o = redisUtils.get(smsRedisKey(vo.getPhone()));
        AssertCustom.notNull(o,"无效验证码");
        AssertCustom.isTrue(vo.getCode().equals(o.toString()),"验证码错误");

        // 交互用户数据
        LoginUserEntity loginUserEntity = new LoginUserEntity();

        // 生成token
        String token = jwtTokenService.createToken(loginUserEntity);
        return ResultData.ok(token);
    }
}
